/*
 * 作者：坚果派
 * 公众号：nutpi
 * 电话：17752170152
 * 官网：https://www.nutpi.net/
 */

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';
import '../../providers/address_provider.dart';
import '../../models/address_model.dart';
import 'package:clipboard/clipboard.dart';

class HierarchicalTab extends StatefulWidget {
  const HierarchicalTab({Key? key}) : super(key: key);

  @override
  State<HierarchicalTab> createState() => _HierarchicalTabState();
}

class _HierarchicalTabState extends State<HierarchicalTab> {
  String? _selectedProvinceCode;
  String? _selectedCityCode;
  String? _selectedAreaCode;
  String? _selectedStreetCode;

  @override
  void initState() {
    super.initState();
    // 页面初始化时加载省份数据
    Future.microtask(() {
      Provider.of<AddressProvider>(context, listen: false)
          .fetchProvinceSimples();
    });
  }

  // 获取当前选中项的名称
  String? _getSelectedProvinceName(AddressProvider provider) {
    if (_selectedProvinceCode == null) return null;
    final province = provider.provinceSimples.firstWhere(
      (p) => p.code == _selectedProvinceCode,
      orElse: () => ProvinceSimple(code: '', name: '未知省份'),
    );
    return province.name;
  }

  String? _getSelectedCityName(AddressProvider provider) {
    if (_selectedCityCode == null) return null;
    final city = provider.cities.firstWhere(
      (c) => c.code == _selectedCityCode,
      orElse: () => CitySimple(code: '', name: '未知城市', provinceCode: ''),
    );
    return city.name;
  }

  String? _getSelectedAreaName(AddressProvider provider) {
    if (_selectedAreaCode == null) return null;
    final area = provider.areas.firstWhere(
      (a) => a.code == _selectedAreaCode,
      orElse: () =>
          AreaSimple(code: '', name: '未知区县', provinceCode: '', cityCode: ''),
    );
    return area.name;
  }

  String? _getSelectedStreetName(AddressProvider provider) {
    if (_selectedStreetCode == null) return null;
    final street = provider.streets.firstWhere(
      (s) => s.code == _selectedStreetCode,
      orElse: () => StreetSimple(
          code: '', name: '未知街道', provinceCode: '', cityCode: '', areaCode: ''),
    );
    return street.name;
  }

  // 重置所有选择
  void _resetAllSelections(AddressProvider provider) {
    setState(() {
      _selectedProvinceCode = null;
      _selectedCityCode = null;
      _selectedAreaCode = null;
      _selectedStreetCode = null;
      provider.clearCities();
      provider.clearAreas();
      provider.clearStreets();
      provider.clearVillages();
    });
    // 重新加载省份数据
    provider.fetchProvinceSimples();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('层级查询'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            tooltip: '重置选择',
            onPressed: () {
              _resetAllSelections(
                  Provider.of<AddressProvider>(context, listen: false));
            },
          ),
        ],
      ),
      body: Consumer<AddressProvider>(
        builder: (context, provider, child) {
          return SingleChildScrollView(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 面包屑导航
                _buildBreadcrumbs(provider),
                const SizedBox(height: 16),

                // 省份选择
                _buildSectionTitle('选择省份'),
                _buildProvinceList(provider),
                const SizedBox(height: 16),

                // 城市选择（仅当选择了省份时显示）
                if (_selectedProvinceCode != null) ...[
                  _buildSectionTitle('选择城市'),
                  _buildCityList(provider),
                  const SizedBox(height: 16),
                ],

                // 区选择（仅当选择了城市时显示）
                if (_selectedCityCode != null) ...[
                  _buildSectionTitle('选择区县'),
                  _buildAreaList(provider),
                  const SizedBox(height: 16),
                ],

                // 街道选择（仅当选择了区时显示）
                if (_selectedAreaCode != null) ...[
                  _buildSectionTitle('选择街道'),
                  _buildStreetList(provider),
                  const SizedBox(height: 16),
                ],

                // 村委会选择（仅当选择了街道时显示）
                if (_selectedStreetCode != null) ...[
                  _buildSectionTitle('选择村委会'),
                  _buildVillageList(provider),
                ],
              ],
            ),
          );
        },
      ),
    );
  }

  // 构建面包屑导航
  Widget _buildBreadcrumbs(AddressProvider provider) {
    final List<Widget> crumbs = [];

    // 添加省份
    final provinceName = _getSelectedProvinceName(provider);
    if (provinceName != null) {
      crumbs.add(
        _buildBreadcrumbItem(
          provinceName,
          onTap: () {
            setState(() {
              _selectedCityCode = null;
              _selectedAreaCode = null;
              _selectedStreetCode = null;
              provider.clearCities();
              provider.clearAreas();
              provider.clearStreets();
              provider.clearVillages();
            });
            provider.fetchCities(_selectedProvinceCode!);
          },
        ),
      );
    }

    // 添加城市
    final cityName = _getSelectedCityName(provider);
    if (cityName != null) {
      if (crumbs.isNotEmpty) {
        crumbs.add(const Text(' > ', style: TextStyle(color: Colors.grey)));
      }
      crumbs.add(
        _buildBreadcrumbItem(
          cityName,
          onTap: () {
            setState(() {
              _selectedAreaCode = null;
              _selectedStreetCode = null;
              provider.clearAreas();
              provider.clearStreets();
              provider.clearVillages();
            });
            provider.fetchAreas(_selectedProvinceCode!, _selectedCityCode!);
          },
        ),
      );
    }

    // 添加区县
    final areaName = _getSelectedAreaName(provider);
    if (areaName != null) {
      if (crumbs.isNotEmpty) {
        crumbs.add(const Text(' > ', style: TextStyle(color: Colors.grey)));
      }
      crumbs.add(
        _buildBreadcrumbItem(
          areaName,
          onTap: () {
            setState(() {
              _selectedStreetCode = null;
              provider.clearStreets();
              provider.clearVillages();
            });
            provider.fetchStreets(
                _selectedProvinceCode!, _selectedCityCode!, _selectedAreaCode!);
          },
        ),
      );
    }

    // 添加街道
    final streetName = _getSelectedStreetName(provider);
    if (streetName != null) {
      if (crumbs.isNotEmpty) {
        crumbs.add(const Text(' > ', style: TextStyle(color: Colors.grey)));
      }
      crumbs.add(
        _buildBreadcrumbItem(
          streetName,
          onTap: () {
            provider.fetchVillages(_selectedProvinceCode!, _selectedCityCode!,
                _selectedAreaCode!, _selectedStreetCode!);
          },
        ),
      );
    }

    if (crumbs.isEmpty) {
      return const SizedBox.shrink();
    }

    return Card(
      elevation: 1,
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Row(
          children: [
            const Icon(Icons.location_on, color: Colors.red, size: 20),
            const SizedBox(width: 8),
            Expanded(
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(children: crumbs),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBreadcrumbItem(String text, {required VoidCallback onTap}) {
    return InkWell(
      onTap: onTap,
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.blue,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12.0),
      child: Row(
        children: [
          Container(
            width: 4,
            height: 20,
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(width: 8),
          Text(
            title,
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
        ],
      ),
    );
  }

  Widget _buildProvinceList(AddressProvider provider) {
    if (provider.loadingProvinceSimples) {
      return const Center(child: CircularProgressIndicator());
    }

    if (provider.provinceSimpleError.isNotEmpty) {
      return _buildErrorWidget(
          provider.provinceSimpleError, () => provider.fetchProvinceSimples());
    }

    if (provider.provinceSimples.isEmpty) {
      return const Text('暂无省份数据');
    }

    return _buildGridList(
      itemCount: provider.provinceSimples.length,
      itemBuilder: (context, index) {
        final province = provider.provinceSimples[index];
        final isSelected = province.code == _selectedProvinceCode;

        return _buildSelectableItem(
          label: province.name,
          isSelected: isSelected,
          onTap: () {
            setState(() {
              _selectedProvinceCode = province.code;
              _selectedCityCode = null;
              _selectedAreaCode = null;
              _selectedStreetCode = null;
              provider.clearCities();
              provider.clearAreas();
              provider.clearStreets();
              provider.clearVillages();
            });
            provider.fetchCities(province.code);
          },
          // trailing: InkWell(
          //   onTap: () async {
          //     try {
          //       final fullAddress = province.name + ' (${province.code})';
          //       await Clipboard.setData(ClipboardData(text: fullAddress));
          //       EasyLoading.showSuccess('复制成功');
          //     } catch (e) {
          //       EasyLoading.showError('复制失败');
          //     }
          //   },
          //   child: const Icon(Icons.content_copy, color: Colors.blue),
          // ),
        );
      },
    );
  }

  Widget _buildCityList(AddressProvider provider) {
    if (provider.loadingCities) {
      return const Center(child: CircularProgressIndicator());
    }

    if (provider.cityError.isNotEmpty) {
      return _buildErrorWidget(provider.cityError, () {
        if (_selectedProvinceCode != null) {
          provider.fetchCities(_selectedProvinceCode!);
        }
      });
    }

    if (provider.cities.isEmpty) {
      return const Text('暂无城市数据');
    }

    return _buildGridList(
      itemCount: provider.cities.length,
      itemBuilder: (context, index) {
        final city = provider.cities[index];
        final isSelected = city.code == _selectedCityCode;

        return _buildSelectableItem(
          label: city.name,
          isSelected: isSelected,
          onTap: () {
            setState(() {
              _selectedCityCode = city.code;
              _selectedAreaCode = null;
              _selectedStreetCode = null;
              provider.clearAreas();
              provider.clearStreets();
              provider.clearVillages();
            });
            provider.fetchAreas(_selectedProvinceCode!, city.code);
          },
        );
      },
    );
  }

  Widget _buildAreaList(AddressProvider provider) {
    if (provider.loadingAreas) {
      return const Center(child: CircularProgressIndicator());
    }

    if (provider.areaError.isNotEmpty) {
      return _buildErrorWidget(provider.areaError, () {
        if (_selectedProvinceCode != null && _selectedCityCode != null) {
          provider.fetchAreas(_selectedProvinceCode!, _selectedCityCode!);
        }
      });
    }

    if (provider.areas.isEmpty) {
      return const Text('暂无区县数据');
    }

    return _buildGridList(
      itemCount: provider.areas.length,
      itemBuilder: (context, index) {
        final area = provider.areas[index];
        final isSelected = area.code == _selectedAreaCode;

        return _buildSelectableItem(
          label: area.name,
          isSelected: isSelected,
          onTap: () {
            setState(() {
              _selectedAreaCode = area.code;
              _selectedStreetCode = null;
              provider.clearStreets();
              provider.clearVillages();
            });
            provider.fetchStreets(
                _selectedProvinceCode!, _selectedCityCode!, area.code);
          },
          // trailing: InkWell(
          //   onTap: () async {
          //     try {
          //       final fullAddress = [
          //             _getSelectedProvinceName(provider),
          //             _getSelectedCityName(provider),
          //             area.name
          //           ].join(' ') +
          //           ' (${area.code})';
          //       await Clipboard.setData(ClipboardData(text: fullAddress));
          //       EasyLoading.showSuccess('复制成功');
          //     } catch (e) {
          //       EasyLoading.showError('复制失败');
          //     }
          //   },
          //   child: const Icon(Icons.content_copy, color: Colors.blue),
          // ),
        );
      },
    );
  }

  Widget _buildStreetList(AddressProvider provider) {
    if (provider.loadingStreets) {
      return const Center(child: CircularProgressIndicator());
    }

    if (provider.streetError.isNotEmpty) {
      return _buildErrorWidget(provider.streetError, () {
        if (_selectedProvinceCode != null &&
            _selectedCityCode != null &&
            _selectedAreaCode != null) {
          provider.fetchStreets(
              _selectedProvinceCode!, _selectedCityCode!, _selectedAreaCode!);
        }
      });
    }

    if (provider.streets.isEmpty) {
      return const Text('暂无街道数据');
    }

    return _buildGridList(
      itemCount: provider.streets.length,
      itemBuilder: (context, index) {
        final street = provider.streets[index];
        final isSelected = street.code == _selectedStreetCode;

        return _buildSelectableItem(
          label: street.name,
          isSelected: isSelected,
          onTap: () {
            setState(() {
              _selectedStreetCode = street.code;
              provider.clearVillages();
            });
            provider.fetchVillages(_selectedProvinceCode!, _selectedCityCode!,
                _selectedAreaCode!, street.code);
          },
          // trailing: InkWell(
          //   onTap: () async {
          //     try {
          //       final fullAddress = [
          //             _getSelectedProvinceName(provider),
          //             _getSelectedCityName(provider),
          //             _getSelectedAreaName(provider),
          //             street.name
          //           ].join(' ') +
          //           ' (${street.code})';
          //       await Clipboard.setData(ClipboardData(text: fullAddress));
          //       EasyLoading.showSuccess('复制成功');
          //     } catch (e) {
          //       EasyLoading.showError('复制失败');
          //     }
          //   },
          //   child: const Icon(Icons.content_copy, color: Colors.blue),
          // ),
        );
      },
    );
  }

  Widget _buildVillageList(AddressProvider provider) {
    if (provider.loadingVillages) {
      return const Center(child: CircularProgressIndicator());
    }

    if (provider.villageError.isNotEmpty) {
      return _buildErrorWidget(provider.villageError, () {
        if (_selectedProvinceCode != null &&
            _selectedCityCode != null &&
            _selectedAreaCode != null &&
            _selectedStreetCode != null) {
          provider.fetchVillages(_selectedProvinceCode!, _selectedCityCode!,
              _selectedAreaCode!, _selectedStreetCode!);
        }
      });
    }

    if (provider.villages.isEmpty) {
      return Container(
        padding: const EdgeInsets.all(16),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Colors.grey.shade300),
        ),
        child: const Text(
          '暂无村委会数据',
          style: TextStyle(fontSize: 16),
        ),
      );
    }

    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey.shade300),
        borderRadius: BorderRadius.circular(8),
      ),
      child: ListView.separated(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: provider.villages.length,
        separatorBuilder: (context, index) => const Divider(height: 1),
        itemBuilder: (context, index) {
          final village = provider.villages[index];
          return ListTile(
            title: Text(
              village.name,
              style: const TextStyle(fontWeight: FontWeight.w500),
            ),
            subtitle: Text('编码: ${village.code}'),
            trailing: InkWell(
              onTap: () async {
                try {
                  final fullAddress = [
                        _getSelectedProvinceName(provider),
                        _getSelectedCityName(provider),
                        _getSelectedAreaName(provider),
                        _getSelectedStreetName(provider),
                        village.name
                      ].join(' ') +
                      ' (${village.code})';
                  await Clipboard.setData(ClipboardData(text: fullAddress));
                  EasyLoading.showSuccess('复制成功');
                } catch (e) {
                  EasyLoading.showError('复制失败');
                }
              },
              child: const Icon(Icons.content_copy, color: Colors.blue),
            ),
            contentPadding:
                const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          );
        },
      ),
    );
  }

  Widget _buildGridList({
    required int itemCount,
    required Widget Function(BuildContext, int) itemBuilder,
  }) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        border: Border.all(color: Colors.grey.shade300),
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          childAspectRatio: 2.5,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
        ),
        itemCount: itemCount,
        itemBuilder: itemBuilder,
      ),
    );
  }

  Widget _buildSelectableItem({
    required String label,
    required bool isSelected,
    required VoidCallback onTap,
    Widget? trailing,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(4),
      child: Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.symmetric(vertical: 8),
        decoration: BoxDecoration(
          color: isSelected
              ? Theme.of(context).primaryColor.withOpacity(0.2)
              : Colors.white,
          borderRadius: BorderRadius.circular(4),
          border: Border.all(
            color: isSelected
                ? Theme.of(context).primaryColor
                : Colors.grey.shade300,
            width: isSelected ? 2 : 1,
          ),
        ),
        child: Stack(
          children: [
            Center(
              child: Text(
                label,
                style: TextStyle(
                  color: isSelected
                      ? Theme.of(context).primaryColor
                      : Colors.black87,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                ),
                textAlign: TextAlign.center,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            if (trailing != null)
              Positioned(
                right: 4,
                top: 0,
                bottom: 0,
                child: trailing,
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorWidget(String errorMessage, VoidCallback onRetry) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.red.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.red.shade200),
      ),
      child: Column(
        children: [
          Row(
            children: [
              Icon(Icons.error_outline, color: Colors.red.shade700),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  '加载失败: $errorMessage',
                  style: TextStyle(color: Colors.red.shade700),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton.icon(
              onPressed: onRetry,
              icon: const Icon(Icons.refresh),
              label: const Text('重试'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red.shade100,
                foregroundColor: Colors.red.shade700,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
